package com.mrjy.payment.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mrjy.common.entity.OrderInfo;
import com.mrjy.common.entity.UserBalanceInfo;
import com.mrjy.common.entity.UserBalancePayment;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.payment.bo.IUserBalancePaymentBo;
import com.mrjy.payment.dto.UserBalancePaymentSchoolDTO;
import com.tencent.common.Util;
import com.tencent.protocol.pay_protocol.ScanPayResData;

@Controller
@RequestMapping("/payment/userBalance")
public class UserBalancePaymentController {

	@Resource
	private IUserBalancePaymentBo userBalancePaymentBo;
	
	/**
	 * 开始订单
	 * @param userBalancePayment
	 * @param session
	 * @return
	 */
	@RequestMapping("/beginPayment")
	@ResponseBody
	public Object beginPayment(UserBalancePayment userBalancePayment,HttpSession session){
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.beginPayment(userBalancePayment,userInfo);
	}
	
	/**
	 * 提交订单
	 * 续费、开通会员 调用
	 * @param userBalancePayment.userId(用户id) userBalancePayment.typeId（充值类型，1余额充值；2会员开通；3福卡激活）
	 * @author csshui isUser=true
	 * @return
	 */
	@RequestMapping("/submitPayment")
	@ResponseBody
	public Object submitPayment(UserBalancePayment userBalancePayment, HttpSession session){
		UserInfo userInfo = ((UserInfo) session.getAttribute(GlobalConstant.USER_INFO));
		return userBalancePaymentBo.txSubmitPayment(userBalancePayment, userInfo);
	}
	/**
	 * 根据订单号获取订单信息
	 * 支付调用的，用于查询订单号和付款金额
	 * @param userBalancePayment.code 订单号
	 * @return
	 * @author csshui isUser=true
	 */
	@RequestMapping("/getPaymentByCode")
	@ResponseBody
	public Object getPaymentByCode(UserBalancePayment userBalancePayment,HttpSession session){
		UserInfo userInfo = ((UserInfo) session.getAttribute(GlobalConstant.USER_INFO));
		if (userInfo != null) {
			return userBalancePaymentBo.getPaymentByCode(userBalancePayment.getCode());
		}
		return "userInfo_error";
	}
	/**
	 * 检查是否已经支付成功
	 * 支付时用于检查是否支付成功 
	 * @param userBalancePayment.code 订单号
	 * @author csshui isUser=true
	 * @return
	 */
	@RequestMapping("/validatePay")
	@ResponseBody
	public Object validatePay(UserBalancePayment userBalancePayment){
		return userBalancePaymentBo.validatePay(userBalancePayment.getCode());
	}
	
	/**
	 * 支付宝页面跳转同步通知
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 * @author csshui isUser=true
	 */
	@RequestMapping("/returnUrl")
	public Object returnUrl(HttpServletRequest request) throws UnsupportedEncodingException {
		// 获取支付宝GET过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		@SuppressWarnings("rawtypes")
		Map requestParams = request.getParameterMap();
		for (@SuppressWarnings("rawtypes")
		Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		// 商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
			
							
		//标志调用接口的类型
			String type =request.getParameter("type");
			if(type!=null){
				type= new String(type.getBytes("ISO-8859-1"), "UTF-8");
			}
			
//			type = "wap";

		String service =request.getParameter("service");
			if(service!=null){
				service= new String(service.getBytes("ISO-8859-1"), "UTF-8");
			}
			
		String exterface =request.getParameter("exterface");
			if(exterface!=null){
				exterface= new String(exterface.getBytes("ISO-8859-1"), "UTF-8");
			}
		
		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		// 付款金额
		String total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"), "UTF-8");
		
		Float money = Float.parseFloat(total_fee);
		UserBalancePayment userBalancePayment = userBalancePaymentBo.txReturnUrl(params, out_trade_no, trade_no, trade_status, money);	
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setUrl(userBalancePayment.getUrl());
		if(type=="wap" || "wap".equals(type)){	
			orderInfo.setMessageString("payment/payment_wap_success");					
		}else if(type=="pc" || "pc".equals(type)){			
			orderInfo.setMessageString(userBalancePayment.getMessageString());					
		}else if(service=="alipay.wap.create.direct.pay.by.user" || "alipay.wap.create.direct.pay.by.user".equals(service)){
			orderInfo.setMessageString("payment/payment_wap_success");	
		}else if (exterface=="create_direct_pay_by_user" || "create_direct_pay_by_user".equals(exterface)){
			orderInfo.setMessageString(userBalancePayment.getMessageString());	
		}else{		
			orderInfo.setMessageString("payment/payment_wap_success");			
		}
		request.setAttribute("orderInfo", orderInfo);
		return orderInfo.getMessageString();
	}
	
	/**
	 * 支付宝服务器异步通知
	 * 
	 * @return
	 * @throws IOException
	 * @author csshui isUser=true
	 */
	@RequestMapping("/notifyUrl")
	@ResponseBody
	public void notifyUrl(HttpServletRequest request,HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		// 商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
			// "gbk");
			params.put(name, valueStr);
		}
		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		// 付款金额
		String total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"), "UTF-8");
		Float money = Float.parseFloat(total_fee);
		String result = userBalancePaymentBo.notifyUrl(params, out_trade_no, trade_no, trade_status, money);
		out.println(result);
		out.flush();
		out.close();
	}
	
	/**
	 * 微信服务器异步通知
	 * 
	 * @return
	 * @throws IOException
	 * @author csshui isUser=true
	 */
	@RequestMapping("/WXnotifyUrl")
	@ResponseBody
	public void WXnotifyUrl(HttpServletRequest request,HttpServletResponse response) throws IOException {
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		System.out.println("微信支付回调数据开始");
		String inputLine;
		String notityXml = "";
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("接收到的报文：" + notityXml);
		// 将返回的XML数据映射到Java对象
		ScanPayResData scanPayResData = (ScanPayResData) Util.getObjectFromXML(notityXml, ScanPayResData.class);
		String resXml = userBalancePaymentBo.WXnotifyUrl(scanPayResData);
		out.write(resXml.getBytes());
		out.flush();
		out.close();
		System.out.println("微信支付回调数据结束");
	}

    /**
     * 微信-pc轮询
     *
     * @return
     * @throws IOException
     * @author csshui isUser=true
     */
    @RequestMapping("/WXPollingNotify")
    @ResponseBody
    public Object WXPollingNotify(ScanPayResData scanPayResData) throws IOException {
        Object resXml = userBalancePaymentBo.WXPollingNotify(scanPayResData);
        return resXml;
    }
	/**
	 * 前台用户订单
	 * @param session
	 * @return
	 */
	@RequestMapping("/getPaymentList")
	@ResponseBody
	public Object getPaymentList(HttpSession session){
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.queryUserBalancePayments(userInfo);
	}
	
	/**
	 * 已支付完成的订单删除标志修改
	 * @param userBalancePayment
	 * @param session
	 * @return
	 */
	@RequestMapping("/updatePaymentFlag")
	@ResponseBody
	public Object updatePaymentFlag(UserBalancePayment userBalancePayment,HttpSession session){
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.updatePaymentFlag(userInfo, userBalancePayment);
	}
	
	@RequestMapping("/deleteByIds")
	@ResponseBody
	public Object deleteByIds(UserBalancePayment userBalancePayment ,HttpSession session){
		UserInfo userInfo = (UserInfo)session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.deleteByIds(userInfo, userBalancePayment.getIds());
	}
	
	/**
	 * 余额支付开通会员
	 * @param userBalanceInfo
	 * @param session
	 * @return
	 */
	@RequestMapping("/balancePay")
	@ResponseBody
	public Object balancePay(UserBalanceInfo userBalanceInfo,HttpSession session){
		UserInfo userInfo = (UserInfo)session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.txBalancePay(userBalanceInfo, userInfo);
	}
	
	/**
	 * 后台分页查询订单明细
	 * @param userBalancePayment
	 * @param session
	 * @return
	 */
	@RequestMapping("/getOrderListByPage")
	@ResponseBody
	public Object getOrderListByPage(UserBalancePayment userBalancePayment,HttpSession session){
		UserInfo userInfo = (UserInfo)session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.getOrderListByPage(userBalancePayment,userInfo);
	}
	
	@RequestMapping("/getOrderStatusList")
	@ResponseBody
	public Object getOrderStatusList(){
		return userBalancePaymentBo.getOrderStatus();
	}
	
	/**
	 * 导出用户订单信息-----------根据typeId导出  1--充值，2--会员缴费 
	 * 						statusId 1、未付款  2、已付款   
	 * 新增 福卡激活导出 typeId 3--福卡激活 add by 2017-04-11
	 * @param userBalancePayment
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("/exportPaymentList")
	@ResponseBody
	public Object exportPaymentList(UserBalancePayment userBalancePayment,HttpServletResponse response,HttpSession session){
		UserInfo userInfo = (UserInfo)session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.exportPaymentList(response,userBalancePayment, userInfo); 
	}
	
	
	/**
	 *导出excel ---新
	 * @return
	 */
	@RequestMapping("/export")
	@ResponseBody
	public Object export(UserBalancePayment userBalancePayment,HttpServletResponse response,HttpSession session){
		return userBalancePaymentBo.exportExl(userBalancePayment,response,session);
	}
	
	/**
	 * 获取支付方式列表
	 * @return
	 */
	@RequestMapping("/getPayMethodList")
	@ResponseBody
	public Object getPayMethodList(){
		return userBalancePaymentBo.getPayMethodList();
	}
	
//	/**
//	 * 检查订单中是否含有未选择年级科目的订单，若有则跳转至年级选择页面
//	 * @return   "ok"---无未选年级订单，无操作，"error"-----有，跳转
//	 */
	/**TODO 涉及到更新操作
	 * 检查订单中有是否未处理年级的，将所有年级都置为1
	 * @param session
	 * @author csshui 作废 
	 * @return  
	 */
	@RequestMapping("/checkPayment")
	@ResponseBody
	public String checkPayment(HttpSession session){
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.checkPaymentNoGrade(userInfo);
	}
	
	/**
	 * 通过学校id分页查询学校推广的用户的付费记录
	 * @param session
	 * @param dto dto.schoolId 学校id ,dto.page ,dto.rows 
	 * @author csshui
	 * @return  
	 */
	@RequestMapping("/querySchoolStudentPaymentBySchoolId")
	@ResponseBody
	public Object querySchoolStudentPaymentBySchoolId(UserBalancePaymentSchoolDTO dto,
			HttpSession session){
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.querySchoolStudentPaymentBySchoolId(dto, userInfo);
	}
	
	/**
	 * 导出学校用户订单信息  
	 * @param userBalancePayment
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("/exportSchoolUserPaymentBack")
	@ResponseBody
	public Object exportSchoolUserPaymentBack(UserBalancePaymentSchoolDTO dto,HttpServletResponse response,HttpSession session){
		UserInfo userInfo = (UserInfo)session.getAttribute(GlobalConstant.USER_INFO);
		return userBalancePaymentBo.exportSchoolUserPaymentBack(response,dto, userInfo); 
	}
	
	
	/**
	 * 更新订单备注
	 * @param userBalancePayment
	 * @return
	 */
	@RequestMapping("/updateOrderNote")
	@ResponseBody
	public Object updateOrderNote(UserBalancePayment userBalancePayment) {
		return userBalancePaymentBo.txUpdateOrderNote(userBalancePayment);
	}
	
	/**
	 * 
	 * @author Javin
	 * @date 2017年12月21日
	 * @desc 判断是否峰会活动折扣期间，新老用户只享受一次优惠活动
	 * @param userBalancePayment
	 * @param session
	 * @return
	 */
	@RequestMapping("/isDuringActivity")
	@ResponseBody
	public Object isDuringActivity(UserBalancePayment userBalancePayment,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		if(userBalancePayment.getId() == null){
			UserInfo info = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
			if(null == info || null == info.getId()){
				map.put("err_code", -1);
				map.put("err_msg", "当前用户会话信息为空");
				return map;
			}
			userBalancePayment.setUserId(info.getId());
		}
		
		return userBalancePaymentBo.isDuringActivity(userBalancePayment,map);
	}
	
	@RequestMapping("/groupByMoney")
	@ResponseBody
	public Object groupByMoney(){
		return userBalancePaymentBo.groupByMoney();
	}
	
	/**
	 * 1.6.8.2特价课程包
	 * 查询特价课程订单 （后台给老师看的）
	 * @param userBalancePayment
	 * @param session
	 * @return
	 */
	@RequestMapping("/querySpecialPayment")
	@ResponseBody
	public Object querySpecialPayment(UserBalancePayment userBalancePayment,HttpSession session){
		return userBalancePaymentBo.querySpecialPayment(userBalancePayment,session);
	}
	
	/**
	 * 导出特价课程包订单
	 * @param userBalancePayment
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("/exportSpecialPayment")
	@ResponseBody
	public Object exportSpecialPayment(UserBalancePayment userBalancePayment,HttpServletResponse response,HttpSession session){
		return userBalancePaymentBo.exportSpecialPayment(userBalancePayment,response,session);
	}

}
